
# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from ragendja.template import render_to_response
from django.template import Context, RequestContext, loader
from django.views.generic.list_detail import object_list
from django.views.generic.simple import direct_to_template
from django.forms.formsets import formset_factory
from haco.models import *
from httpauth import *
from haco.jsTime import *
from haco.convert import *
import logging
import time
import csv



@http_login_required()
def record( request):

    logging.info(request.user.username + ":" + request.GET['pnum'])
    
    mes ="<html><body>"
    
    haco =Haco(key_name= now().strftime("%Y-%m-%d")
               + ":" + str(request.GET['pnum'])
               + ":"  + request.user.username)
    haco.user  =request.user
    haco.username =request.user.username
    haco.date  =  today()

    if request.GET['pnum'] == "0":
        if now().strftime("%H") == "23":
            haco.date = tomorrow()
    
    haco.timestamp = now()
    mes +=request.user.username+"<br/>"

    if request.GET.has_key( 'pnum'):
        haco.pnum =int( request.GET['pnum'])
        mes +="pnum:"+str(haco.pnum)+"<br/>"

    if request.GET.has_key( 'temp'):
        haco.temp =float( v2T(request.GET['temp']))
        mes +="temp:"+str(haco.temp)+"<br/>"
        
    if request.GET.has_key( 'light'):
        haco.light =float( v2L(request.GET['light']))
        mes +="light:"+str(haco.light)+"<br/>"

    if request.GET.has_key( 'watt'):
        haco.watt  =float( v2W(request.GET['watt']))
        mes +="watt:"+str(haco.watt)+"<br/>"
    mes +="</body></html>"
    
    haco.put()
    

    
    return HttpResponse( mes)

@login_required()
def report( request):

    delta = 0
    if request.GET.has_key( 'delta'):
        delta = int(request.GET['delta'])
        day = someday(delta)
    else:
        day = today()

    t_list = [-1.0] * 144
    l_list = [-1.0] * 144
    w_list = [-1.0] * 144
     
    q =Haco.all()
    q =q.filter( 'user', request.user)
    q =q.filter( 'date', day)
    q =q.order( 'pnum')
    
    for h in q:
        t_list[h.pnum] = h.temp
        l_list[h.pnum] = h.light
        w_list[h.pnum] = h.watt

    if max(w_list) < 200:
        w_scale = 200
        w_line  = 25
    else:
        w_scale = 1000
        w_line  = 20
        
    return direct_to_template(request, 'report.html',
        {
        'day'   : day.strftime("%m/%d"),
        'delta' : delta,
        'prev_url'   : "./?delta="+str(delta -1 ),
        'next_url'   : "./?delta="+str(delta +1 ),
        't_list': chartmake(t_list),
        'l_list': chartmake(l_list),
        'w_list': chartmake(w_list),
        'w_scale': w_scale,
        'w_line':  w_line,
        })


def chartmake( a_list):
    chart =""
    for data in a_list:
        chart += str(data) +","
    chart = chart[0:len(chart)-1]
    return chart

@login_required()
def matrix( request):

    if request.GET.has_key( 'delta'):
        day = someday(int(request.GET['delta']))
    else:
        day = today()
    
    q =Haco.all()
    q =q.filter( 'user', request.user)
    q =q.filter( 'date', day)
    q =q.order( 'pnum')

    return object_list( request, q)


@login_required
def map( request):
    
    return direct_to_template(request, 'map.html',
        {
        'ido': str(36.054148),
        'kdo': str(140.140033),
        })


@login_required
def feed( request):

    delta = 0
    if request.GET.has_key( 'delta'):
        delta = int(request.GET['delta'])
        day = someday(delta)
    else:
        day = today()

    q =Haco.all()
    q =q.filter( 'user', request.user)
    q =q.filter( 'date', day)
    q =q.order( 'pnum')
    
    
    return object_list( request, queryset=q ,template_name="feed.xml"
                        ,extra_context = {'date':day.strftime("%Y-%m-%d"),
                                          'username':request.user.username}
                        ,mimetype="application/xml")

@login_required
def csv( request):

    delta = 0
    if request.GET.has_key( 'delta'):
        delta = int(request.GET['delta'])
        day = someday(delta)
    else:
        day = today()
        
    mes =""
    q =Haco.all()
    q =q.filter( 'user', request.user)
    q =q.filter( 'date', day)
    q =q.order( 'pnum')
    mes = ""
    for h in q:
        mes += str(h.username)+","
        mes += str(h.date)+","
        mes += str(h.pnum)+","
        mes += str(h.light)+","
        mes += str(h.temp)+","
        mes += str(h.watt)+","
        mes += str(h.timestamp)
        mes +="\n"

    return HttpResponse(mes,mimetype = "text/plain" )




@login_required
def test( request):
    if request.GET.has_key( 'delta'):
        day = someday(int(request.GET['delta']))
    else:
        day = today()
    
    q =Haco.all()
    q =q.filter( 'user', request.user)
    q =q.filter( 'date', day)
    q =q.order( 'pnum')

    return object_list( request, q, template_name = "test.html",
                        extra_context ={
                            'count': len(q),
                            }
                        )
